package com.adayo.memoryfree.activity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.adayo.memoryfree.R;
import com.adayo.memoryfree.adapter.ClearMemoryAdapter;
import com.adayo.memoryfree.base.BaseSwipeBackActivity;
import com.adayo.memoryfree.bean.AppProcessInfo;
import com.adayo.memoryfree.bean.StorageSize;
import com.adayo.memoryfree.quickreturn.enums.QuickReturnType;
import com.adayo.memoryfree.quickreturn.listeners.QuickReturnListViewOnScrollListener;
import com.adayo.memoryfree.service.CoreService;
import com.adayo.memoryfree.utils.JToastKit;
import com.adayo.memoryfree.utils.JStorageKit;
import com.adayo.memoryfree.waveview.WaveView;
import com.adayo.memoryfree.widgets.TitleView;
import com.adayo.memoryfree.widgets.textcounter.CounterView;
import com.adayo.memoryfree.widgets.textcounter.formatters.DecimalFormatter;
import com.nhaarman.listviewanimations.itemmanipulation.swipedismiss.OnDismissCallback;

import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;

public class MemoryCleanActivity extends BaseSwipeBackActivity implements OnDismissCallback, CoreService.OnProcessActionListener {

	@ViewInject(R.id.tv_title)
	private TitleView titleView;
	@ViewInject(R.id.listview)
	ListView mListView;
	@ViewInject(R.id.wave_view)
	WaveView mwaveView;
	@ViewInject(R.id.header)
	RelativeLayout header;
	List<AppProcessInfo> mAppProcessInfos = new ArrayList<>();
	ClearMemoryAdapter mClearMemoryAdapter;

	@ViewInject(R.id.textCounter)
	CounterView textCounter;
	@ViewInject(R.id.sufix)
	TextView sufix;
	public long Allmemory;

	@ViewInject(R.id.bottom_lin)
	LinearLayout bottom_lin;

	@ViewInject(R.id.progressBar)
	View mProgressBar;
	@ViewInject(R.id.progressBarText)
	TextView mProgressBarText;

	@ViewInject(R.id.clear_button)
	Button clearButton;

	private CoreService mCoreService;

	private ServiceConnection mServiceConnection = new ServiceConnection() {
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			mCoreService = ((CoreService.ProcessServiceBinder) service).getService();
			mCoreService.setOnActionListener(MemoryCleanActivity.this);
			mCoreService.scanRunProcess();
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			mCoreService.setOnActionListener(null);
			mCoreService = null;
		}
	};

	@Override
	protected int getLayoutId() {
		return R.layout.activity_memory_clean;
	}

	@Override
	protected void initParams(Bundle savedInstanceState) {
		titleView.setResource(R.drawable.selector_return_btn,
				R.string.app_memory_clean);
		titleView.setLeftClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});

		mClearMemoryAdapter = new ClearMemoryAdapter(context, mAppProcessInfos);
		mListView.setAdapter(mClearMemoryAdapter);
		bindService(new Intent(context, CoreService.class),
				mServiceConnection, Context.BIND_AUTO_CREATE);
		int footerHeight = context.getResources().getDimensionPixelSize(R.dimen.footer_height);
		mListView.setOnScrollListener(new QuickReturnListViewOnScrollListener(QuickReturnType.FOOTER, null, 0, bottom_lin, footerHeight));
		textCounter.setAutoFormat(false);
		textCounter.setFormatter(new DecimalFormatter());
		textCounter.setAutoStart(false);
		textCounter.setIncrement(5f); // the amount the number increments at each time interval
		textCounter.setTimeInterval(50); // the time interval (ms) at which the text changes
	}

	@Override
	protected String[] initPermissions() {
		return new String[0];
	}

	@Event(value = {R.id.clear_button})
	private void onViewClick(View v) {
		long killAppmemory = 0;

		for (int i = mAppProcessInfos.size() - 1; i >= 0; i--) {
			if (mAppProcessInfos.get(i).checked) {
				killAppmemory += mAppProcessInfos.get(i).memory;
				mCoreService.killBackgroundProcesses(mAppProcessInfos.get(i).processName);
				mAppProcessInfos.remove(mAppProcessInfos.get(i));
				mClearMemoryAdapter.notifyDataSetChanged();
			}
		}
		Allmemory = Allmemory - killAppmemory;
		//JToastKit.getInstance().showMessage("共清理" + JStorageKit.convertStorage(killAppmemory) + "内存");
		if (Allmemory > 0) {
			refeshTextCounter();
		}
	}

	@Override
	public void onScanStarted(Context context) {
		mProgressBarText.setText(R.string.scanning);
		showProgressBar(true);
	}

	@Override
	public void onScanProgressUpdated(Context context, int current, int max) {
		mProgressBarText.setText(getString(R.string.scanning_m_of_n, current, max));
	}

	@Override
	public void onScanCompleted(Context context, List<AppProcessInfo> apps) {
		mAppProcessInfos.clear();

		Allmemory = 0;
		for (AppProcessInfo appInfo : apps) {
			if (!appInfo.isSystem) {
				mAppProcessInfos.add(appInfo);
				Allmemory += appInfo.memory;
			}
		}

		refeshTextCounter();
		mClearMemoryAdapter.notifyDataSetChanged();
		showProgressBar(false);

		if (apps.size() > 0) {
			header.setVisibility(View.VISIBLE);
			bottom_lin.setVisibility(View.VISIBLE);
		} else {
			header.setVisibility(View.GONE);
			bottom_lin.setVisibility(View.GONE);
		}
	}

	private void showProgressBar(boolean show) {
		if (show) {
			mProgressBar.setVisibility(View.VISIBLE);
		} else {
			mProgressBar.startAnimation(AnimationUtils.loadAnimation(
					context, android.R.anim.fade_out));
			mProgressBar.setVisibility(View.GONE);
		}
	}

	private void refeshTextCounter() {
		mwaveView.setProgress(20);
		StorageSize mStorageSize = JStorageKit.convertStorageSize(Allmemory);
		textCounter.setStartValue(0f);
		textCounter.setEndValue(mStorageSize.value);
		sufix.setText(mStorageSize.suffix);
		//  textCounter.setSuffix(mStorageSize.suffix);
		textCounter.start();
	}

	@Override
	public void onCleanStarted(Context context) {

	}

	@Override
	public void onCleanCompleted(Context context, long cacheSize) {

	}

	@Override
	public void onDismiss(@NonNull ViewGroup listView, @NonNull int[] reverseSortedPositions) {

	}

	@Override
	public void onDestroy() {
		unbindService(mServiceConnection);
		super.onDestroy();
	}
}
